package edu.rpi.bt.client;

import java.util.Iterator;
import java.util.List;

import com.apress.progwt.client.college.ServiceCache;
import com.apress.progwt.client.domain.User;
import com.apress.progwt.client.rpc.StdAsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.ArrayReader;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.IntegerFieldDef;
import com.gwtext.client.data.MemoryProxy;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Toolbar;
import com.gwtext.client.widgets.ToolbarButton;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.event.GridRowListener;

import edu.rpi.bt.client.domain.Destination;


public class BananaManager extends Panel {
 
    private ServiceCache serviceCache;

    private User thisUser;
    private List<Destination> trips;

    private String messages = "";
    private GridPanel grid = new GridPanel( );  
    
    private BananaManager thisManager = this;
    private AppBananaManager app;
    
    private Store store; 
    private Boolean isReload = false;
    
    public BananaManager( AppBananaManager banMan ){
        this.app = banMan;
        serviceCache = banMan.getServiceCache();
        init(serviceCache);
    }
     
   private void buildPanel(){
        setBorder(false);  
        setPaddings(15);  
        setWidth(750);
  
         final ManageTripWindow window = new ManageTripWindow( serviceCache );  
         window.setTripManager(this);
   
         RecordDef recordDef = new RecordDef(  
                 new FieldDef[]{  
                         new StringFieldDef("tripname"),  
                         new StringFieldDef("description"),  
                         new IntegerFieldDef("locationId")  
                 }  
         );
         
         Object[][] data = getTripData();  
         MemoryProxy proxy = new MemoryProxy(data);  
   
         ArrayReader reader = new ArrayReader(recordDef);  
         store = new Store(proxy, reader);  
         store.load();  
         grid.setStore(store);  
   
   
         ColumnConfig[] columns = new ColumnConfig[]{  
                 new ColumnConfig("Trip Name", "tripname", 160, true, null, "tripname"),  
                 new ColumnConfig("Trip Description", "description", 400, false, null, "description")  
//                 new ColumnConfig("", "locationId", 0, false, null, "locationId")
         };  
   
         ColumnModel columnModel = new ColumnModel(columns);  
         grid.setColumnModel(columnModel);  
   
         grid.setFrame(true);  
         grid.setStripeRows(true);  
         grid.setAutoExpandColumn("tripname");  
         grid.setAutoExpandColumn("description");  
          
         grid.setTitle("Manage Your Trips");  

         grid.addGridRowListener(new GridRowListener() {  
             public void onRowClick(GridPanel grid, int rowIndex, EventObject e) {  
             }  
   
             public void onRowDblClick(GridPanel grid, int rowIndex, EventObject e) {
                 long locId = (long) grid.getStore().getRecordAt(rowIndex).getAsInteger("locationId");
                 

                 ManageTripWindow mtw = new ManageTripWindow(rowIndex, trips.get(rowIndex), serviceCache);
                 mtw.setTripManager(thisManager );
                 mtw.show();
             }  
   
             public void onRowContextMenu(GridPanel grid, int rowIndex, EventObject e) {  
             }  
         });
         
         Toolbar bottomToolbar = new Toolbar();  
         bottomToolbar.addFill();  
         bottomToolbar.addButton(new ToolbarButton("Add A Trip", new ButtonListenerAdapter() {  
             public void onClick(Button button, EventObject e) {  
                 window.show(button.getId());  
             }  
         }));  
         grid.setBottomToolbar(bottomToolbar);  
   
         add(grid);  
         
         // This is really screwy and nasty.
         // It's the only way I could get the thing to appear after waiting for the callback
         // from the async to get Destinations
         this.app.loadGUI(this);
     }  
  
    private void init(ServiceCache servCache){
        this.serviceCache = servCache;
        

        serviceCache
        .getCurrentUser(new StdAsyncCallback<User>("Get User") {

            public void onSuccess(User result) {
                super.onSuccess(result);
                if (result == null) {
                 
                } else {
                   
                    load(result);
                }
            }

            public void onFailure(Throwable caught) {
                super.onFailure(caught);
              
            }
        });
        
       
       
        serviceCache.getAllTrips(new StdAsyncCallback<List<Destination>>("Get dests"){
            public void onSuccess(List<Destination> result) {
                super.onSuccess(result);
                if (result == null) {
                    MessageBox.alert("result for trip null"); 
                } else {
                    load(result);
                    
                    if( !isReload ){
                        buildPanel();
                    } else {
                        updateDataStore();
                    }
                }
            }

            public void onFailure(Throwable caught) {
                super.onFailure(caught);
              
            }
        });
    }
    
        public void load(User user){
            this.thisUser=user;
     //       this.destinations=(List<Destination>) user.getDestinations();
        }
        public void load(List<Destination> dests){
            this.trips=dests;
            for (Iterator it = trips.iterator(); it.hasNext(); ) {
                Destination trip = (Destination)it.next();
                messages += "Trip Name " + trip.getName() + " Trip Description " + trip.getDescription() + "<br>";
             }
            
        }
        
        public  List<Destination> getDestinations(){
            MessageBox.alert("inside get destination"); 
            return this.trips;
        }
        
     private Object[][] getTripData() {  
         Object[][] tmp = new Object[][]{};
         
         for (Iterator it = trips.iterator(); it.hasNext(); ) {
             Destination trip = (Destination)it.next();
             tmp[tmp.length] = new Object[]{
                     trip.getName(), trip.getDescription(), trip.getId()
             };
          }
         
        return tmp;
     }
     
     public void reinitTripManager(){
         isReload = true;
         init(serviceCache);
     }
     
     public void updateDataStore(){
         Object[][] data = getTripData();  
         MemoryProxy proxy = new MemoryProxy(data);
         store.setDataProxy(proxy);
         store.reload();
     }     
}
